#!/usr/bin/env python3

# Copyright (c) 2005-2014 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

import os
import time
import selenium
from utils import Util
from config import Config


class Category:

    def __init__(self):
        self._productId = None
        self._bDownloadUpdate = False
        self._bDownloadDrivers = False

    def get_category_id(self):
        return "win7"

    def get_category_name(self):
        return "Microsoft Windows 7"

    def get_category_cmdline_option_description(self):
        buf = ""
        buf += '--updates: download all updates.\n'
        buf += '--drivers: download all drivers.\n'
        return buf

    def set_product_and_parse_cmdline(self, productId, argv, c, dieFunc):
        self._productId = productId

        while len(argv) > c:
            if argv[c] == "--updates":
                self._bDownloadUpdate = True
                c += 1
                continue
            elif argv[c] == "--drivers":
                self._bDownloadDrivers = True
                c += 1
                continue
            else:
                break

        return c

    def get_product_id_list(self):
        ret = []

        t = [
            "windows-7-starter.x86.en-us",
            "windows-7-home-basic.x86.en-us",
            "windows-7-home-premium.x86.en-us",
            "windows-7-professional.x86.en-us",
            "windows-7-ultimate.x86.en-us",
            "windows-7-enterprise.x86.en-us",
        ]
        ret += t
        ret += [x.replace("x86", "x86_64") for x in t]

        return ret

    def get_product_description(self, product_id):
        ret = ""
        edition, arch, lang = product_id.split(".")

        d = {
            "windows-7-starter":       "Microsoft Windows 7 Starter",
            "windows-7-home-basic":    "Microsoft Windows 7 Home Basic",
            "windows-7-home-premium":  "Microsoft Windows 7 Home Premium",
            "windows-7-professional":  "Microsoft Windows 7 Professional",
            "windows-7-ultimate":      "Microsoft Windows 7 Ultimate",
            "windows-7-enterprise":    "Microsoft Windows 7 Enterprise",
        }
        ret += d[edition]
        ret += ", "

        d = {
            "x86":    "X86",
            "x86_64": "X86_64",
        }
        ret += d[arch]
        ret += ", "

        d = {
            "en-us": "en-US",
            "fr-ca": "fr-CA",
            "pt-br": "pt-BR",
            "pt-pt": "pt-PT",
            "zh-cn": "zh-CN",
            "zn-tw": "zh-TW",
        }
        if lang in d:
            ret += d[lang]
        else:
            ret += lang

        return ret

    def download(self, cacheDir, destDir):
        localFile = _Win7.download(self._productId, cacheDir)
        finalFile = os.path.join(destDir, self._productId + ".iso")
        Util.copyFile(localFile, finalFile, os.getuid(), os.getgid())


class _Win7:

    @staticmethod
    def get_url_and_fn(productId):
        # from https://techpp.com/2018/04/16/windows-7-iso-official-direct-download-links

        if productId == "windows-7-home-premium.x86.en-us":
            return ("https://download.microsoft.com/download/E/D/A/EDA6B508-7663-4E30-86F9-949932F443D0/7601.24214.180801-1700.win7sp1_ldr_escrow_CLIENT_HOMEPREMIUM_x86FRE_en-US.iso", None)
        if productId == "windows-7-home-premium.x86_64.en-us":
            return ("https://download.microsoft.com/download/E/A/8/EA804D86-C3DF-4719-9966-6A66C9306598/7601.24214.180801-1700.win7sp1_ldr_escrow_CLIENT_HOMEPREMIUM_x64FRE_en-US.iso", None)
        if productId == "windows-7-professional.x86.en-us":
            return ("https://download.microsoft.com/download/C/0/6/C067D0CD-3785-4727-898E-60DC3120BB14/7601.24214.180801-1700.win7sp1_ldr_escrow_CLIENT_PROFESSIONAL_x86FRE_en-US.iso", None)
        if productId == "windows-7-professional.x86_64.en-us":
            return ("https://download.microsoft.com/download/0/6/3/06365375-C346-4D65-87C7-EE41F55F736B/7601.24214.180801-1700.win7sp1_ldr_escrow_CLIENT_PROFESSIONAL_x64FRE_en-US.iso", None)
        if productId == "windows-7-ultimate.x86.en-us":
            return ("https://download.microsoft.com/download/1/E/6/1E6B4803-DD2A-49DF-8468-69C0E6E36218/7601.24214.180801-1700.win7sp1_ldr_escrow_CLIENT_ULTIMATE_x86FRE_en-US.iso", None)
        if productId == "windows-7-ultimate.x86_64.en-us":
            return ("https://download.microsoft.com/download/5/1/9/5195A765-3A41-4A72-87D8-200D897CBE21/7601.24214.180801-1700.win7sp1_ldr_escrow_CLIENT_ULTIMATE_x64FRE_en-US.iso", None)

        if productId.startswith("windows-7-enterprise-"):
            if productId == "windows-7-enterprise.x86.en-us":
                url = "https://idatavn-my.sharepoint.com/:u:/g/personal/data01_phanmemchat_net/Eec-CsxcwntJkpS_qCnrYPEBp5GFlChmzzfFAlisjR96Kw?e=fpr76R"
            elif productId == "windows-7-enterprise.x86_64.en-us":
                url = "https://idatavn-my.sharepoint.com/:u:/g/personal/data01_phanmemchat_net/EbQ80EYnmyNFqprGKPmf3xgBzyHkeLvPTeGOpvhmePYh5Q?e=lwMDXi"
            else:
                assert False

            browser = selenium.webdriver.WebKitGTK()
            browser.implicitly_wait(60)
            try:
                browser.get(url)
                time.sleep(5)

                button = browser.find_elements_by_xpath("//button[class='od-Button od-ButtonBarCommand od-ButtonBarCommand--button']")[1]
                button.click()

                return (url, productId + ".iso")
            finally:
                browser.quit()

    @classmethod
    def download(cls, productId, downloadDir):
        url, fn = _Win7.get_url_and_fn(productId)
        localFile = cls._fetchInstallIsoFileSimple(url, downloadDir, fn=fn)
        return localFile

    @classmethod
    def _fetchInstallIsoFileSimple(cls, url, downloadDir, fn=None, digest=None):
        if fn is None:
            fn = os.path.basename(url)

        if digest is not None:
            digestAlgo = "sha256"
        else:
            digestAlgo = None

        localFile = os.path.join(downloadDir, fn)
        Util.checkAndFetchHttp(localFile, [url], digest, digestAlgo, Config.checksumMaxTries, Config.verboseLevel)

        return localFile
